import {
  login,
  logout
} from '@/api/user'

const getDefaultState = () => {
  return {
    name: '',
    avatar: '',
    roles: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({
    commit
  }, userInfo) {
    const {
      userName,
      passWord
    } = userInfo
    return new Promise((resolve, reject) => {
      login({
        userName: userName.trim(),
        passWord: passWord
      }).then(response => {
        // const { data } = response
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({
    commit,
    state
  }) {
    return new Promise((resolve, reject) => {
      const data = sessionStorage.getItem('USERACCOUNT')
      logout({
        userAccount: data
      }).then(() => {
        sessionStorage.removeItem('PERTYPE')
        sessionStorage.removeItem('USERID')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
